using Abp.Linq.Extensions;
using Abp.Extensions;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Enterprise.Entities.Dtos;
using Abp.Domain.Repositories;
using HCD.Entities.Dtos;
using HCD.Entities;
using HCD.Project.Dtos;
using HCD.Dtos;
using Abp.Application.Services.Dto;
using Microsoft.AspNetCore.Mvc;
using Abp.Application.Services;

namespace HCD.Project
{
    /// <summary>
    /// PeojectPersonal应用层服务的接口实现方法
    ///</summary>
    [Route("api/[controller]/[action]"),RemoteService(false)]
    public class ProjectAppService : EnterpriseAppServiceBase, IProjectAppService
    {
        public IRepository<ProjectPersonal, int> ProjectPersonalRepository { get; set; }
        public IRepository<Requirement, int> RequirementRepository { get; set; }
        public IRepository<ProjectTeam, int> ProjectTeamRepository { get; set; }
        public IRepository<ProjectTeamOperator, int> ProjectTeamOperatorRepository { get; set; }
        //视图
        //public IRepository<ViewTest, int> ViewTest { get; set; }
        /// <summary>
        /// 保存个人项目经验
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ProjectPersonalEditDto> SaveProjectPersonal(ProjectPersonalEditDto input)
        {
            if (input.Id.HasValue)
            {
                var entity = await ProjectPersonalRepository.GetAsync(input.Id.Value);
                //不知道咋回事，tenantid覆盖了
                //entity = ObjectMapper.Map<ProjectPersonal>(input);
                //entity.TenantId = CurrentUnitOfWork.GetTenantId().Value;
                //需要简化
                entity.ProjectTitle = input.ProjectTitle;
                entity.ProjectTags = input.ProjectTags;
                entity.EnvironmentDevTags = input.EnvironmentDevTags;
                entity.EnvironmentOSTags = input.EnvironmentOSTags;
                entity.ClientTags = input.ClientTags;
                entity.ProjectDescription = input.ProjectDescription;
                entity.UpdateTime = DateTime.Now;
                await ProjectPersonalRepository.UpdateAsync(entity);
                var dto = ObjectMapper.Map<ProjectPersonalEditDto>(entity);
                return dto;
            }
            else
            {
                var entity = ObjectMapper.Map<ProjectPersonal>(input);
                entity = await ProjectPersonalRepository.InsertOrUpdateAsync(entity);
                entity.CreateTime = DateTime.Now;
                var dto = ObjectMapper.Map<ProjectPersonalEditDto>(entity);
                return dto;
            }
        }
        /// <summary>
        /// 删除个人项目经验
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<bool> DelProjectPersonal(int id)
        {
            await ProjectPersonalRepository.DeleteAsync(id);
            return true;
        }
        /// <summary>
        /// 获取个人项目列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PagedResultDto<ProjectPersonalListDto>> GetProjectPersonal([FromBody] GetProjectPersonalInput input)
        {
            try
            {
                //db entity demo
                var query = ProjectPersonalRepository.GetAll();
                //view entity demo
                //var query = ViewTest.GetAll();
                var data = query.ToList();
                if (!input.Query.IsNullOrEmpty())
                    query = query.Where(p => p.ProjectTitle.Contains(input.Query) || p.ProjectDescription.Contains(input.Query) || p.ProjectTags.Contains(input.Query));
                // TODO:根据传入的参数添加过滤条件
                var dataCount = await query.CountAsync();
                var dataQuery = query
                        .Where(p => p.OperatorID.ToString() == input.OperatorID).OrderByDescending(p => p.Id)
                        .PageBy(input);

                var dataListDtos = await ObjectMapper.ProjectTo<ProjectPersonalListDto>(dataQuery).ToListAsync();

                return new PagedResultDto<ProjectPersonalListDto>(
                        dataCount,
                        dataListDtos
                    );
            }
            catch (Exception ex)
            {

                throw;
            }

        }
        /// <summary>
        /// 获取人力资源池
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<OperatorPoolListDto>> GetOperatorPool()
        {
            var result = new List<OperatorPoolListDto>();

            //var query = (from op in _operatorRepository.GetAll()
            //             join pp in _projectPersonalRepository.GetAll() on op.Id equals pp.OperatorID into pp_all
            //             from pp in pp_all.DefaultIfEmpty()
            //             where op.AuditStatus == 1
            //             orderby pp_all.Count() descending
            //             select new
            //             {
            //                 op,
            //                 ProjectJoinCount = pp_all.Count()
            //             })
            //             .GroupBy(p => p.op.Id);
            //var group = await query.ToListAsync();
            //group?.ForEach(p =>
            //{
            //    var item = ObjectMapper.Map<OperatorPoolListDto>(p.FirstOrDefault().op);
            //    item.ProjectJoinCount = p.FirstOrDefault().ProjectJoinCount;
            //    result.Add(item);
            //});
            return result;
        }
        /// <summary>
        /// 获取项目资源池
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<PagedResultDto<ProjectPoolListDto>> GetProjectPool(PagedAndSortedInputDto input)
        {
            var query = ProjectPersonalRepository.GetAll();
            if (!input.Query.IsNullOrEmpty())
                query = query.Where(p => p.ProjectTitle.Contains(input.Query) || p.ProjectDescription.Contains(input.Query) || p.ProjectTags.Contains(input.Query));
            // TODO:根据传入的参数添加过滤条件
            var dataQuery = query
                    .OrderByDescending(p => p.CreateTime)
                    .PageBy(input);
            var dataCount = await query.CountAsync();
            var dataListDtos = await ObjectMapper.ProjectTo<ProjectPoolListDto>(dataQuery).ToListAsync();

            return new PagedResultDto<ProjectPoolListDto>(
                    dataCount,
                    dataListDtos
                );
        }
        /// <summary>
        /// 获取需求资源池
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<PagedResultDto<RequirementPoolListDto>> GetRquirementPool(PagedAndSortedInputDto input)
        {
            var query = RequirementRepository.GetAll();
            if (!input.Query.IsNullOrEmpty())
                query = query.Where(p => p.ProjectTitle.Contains(input.Query) || p.ProjectDescription.Contains(input.Query) || p.ProjectTags.Contains(input.Query));
            // TODO:根据传入的参数添加过滤条件
            var dataQuery = query
                    .OrderByDescending(p => p.CreateTime)
                    .PageBy(input);
            var dataCount = await query.CountAsync();
            var dataListDtos = await ObjectMapper.ProjectTo<RequirementPoolListDto>(dataQuery).ToListAsync();

            return new PagedResultDto<RequirementPoolListDto>(
                    dataCount,
                    dataListDtos
                );

        }
        /// <summary>
        /// 获取个人发布的需求列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<GetMyRequirementListDto>> GetMyRequirement(Guid id)
        {
            var query = RequirementRepository.GetAll().Where(p => p.CreateOperator == id).OrderByDescending(p => p.CreateTime);
            return await ObjectMapper.ProjectTo<GetMyRequirementListDto>(query).ToListAsync();
        }
        /// <summary>
        /// 发布个人需求
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ProjectPersonalEditDto> SaveMyRequirement(RequirementEditDto input)
        {
            var entity = ObjectMapper.Map<Requirement>(input);
            entity = await RequirementRepository.InsertOrUpdateAsync(entity);

            var dto = ObjectMapper.Map<ProjectPersonalEditDto>(entity);
            return dto;
        }
        /// <summary>
        /// 获取个人发布的需求列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<ProjectTeamEditDto>> GetMyProjectTeam(Guid id)
        {
            var query = ProjectTeamRepository.GetAll().Where(p => p.CreateOperator == id).OrderByDescending(p => p.CreateTime);
            return await ObjectMapper.ProjectTo<ProjectTeamEditDto>(query).ToListAsync();
        }
        /// <summary>
        /// 发布个人需求
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> SaveMyProjectTeam(ProjectTeamEditDto input)
        {
            //delete detail
            if (input.Id.HasValue)
                await ProjectTeamOperatorRepository.DeleteAsync(p => p.ProjectTeamID == input.Id);
            var entity = ObjectMapper.Map<ProjectTeam>(input);
            var project = await ProjectTeamRepository.InsertOrUpdateAsync(entity);

            input.ProjectTeamOperatorList?.ForEach(async p =>
            {
                var pp = ObjectMapper.Map<ProjectTeamOperator>(p);
                pp.ProjectTeamID = entity.Id;
                pp.UpdateTime = DateTime.Now;
                await ProjectTeamOperatorRepository.InsertAsync(pp);
            });

            return true;
        }
        /// <summary>
        /// 获取我参与的所有团队项目
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<ProjectTeamListDto>> GetMyJoinProjectTeam(Guid id)
        {
            var projectTeamList = new List<ProjectTeamListDto>();
            var query = from pt in ProjectTeamRepository.GetAll()
                        join pto in ProjectTeamOperatorRepository.GetAll() on pt.Id equals pto.ProjectTeamID
                        where pto.OperatorID == id
                        orderby pt.CreateTime
                        select new
                        {
                            pt,
                            pto
                        };
            var group = (await query.ToListAsync()).GroupBy(p => p.pt?.Id).ToList();
            group?.ForEach(p =>
            {
                var projectTeam = ObjectMapper.Map<ProjectTeamListDto>(p.First().pt);
                projectTeam.ProjectTeamOperatorList = ObjectMapper.Map<List<ProjectTeamOperatorListDto>>(p.Select(pp => pp.pto));
                projectTeamList.Add(projectTeam);
            });
            return projectTeamList;
        }
    }
}


